import React, { useEffect, useState, useRef } from 'react'
import { PageContainer } from '@ant-design/pro-components'
import { useModel, history } from '@umijs/max'
import { Form, Checkbox, Space, Button, Card, Divider, Input, Radio, InputNumber, Select, Cascader, App } from 'antd'
import styles from './Settings.less'

const CheckboxGroup = Checkbox.Group
const formItemLayout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 22 }
}

export default () => {
  const { GetRiskOptions } = useModel('BaseSet')

  const getDefaultFormList = () => {
    return [
      {
        title: '风控设置',
        type: 'wrapper',
        children: [
          {
            title: '风控覆盖',
            type: 'checkbox',
            formProp: {
              name: 'risk_type',
              label: '风控覆盖',
              rules: [{ required: true, message: '请选择风控覆盖！' }]
            },
            itemProp: {
              options: riskOptions
            }
          }
        ]
      },
  
      //-----------
      {
        title: '运营配置',
        type: 'wrapper',
        children: [
          {
            title: '增值服务默认勾选',
            type: 'radio',
            visibelCheck: true,
            formProp: {
              name: 'force_select_gain',
              label: '增值服务默认勾选',
              rules: [{ required: true }],
              help: '启用后将为用户默认勾选增值服务'
            },
            itemProp: {
              prop: {},
              list: [
                {
                  label: '启用',
                  value: 1
                },
                {
                  label: '禁用',
                  value: 0
                }
              ]
            }
          }
        ]
      }
    ]
  }

  const [form] = Form.useForm()
  const { SaveBasicSet, GetBasicSet } = useModel('BaseSet')

  const { message } = App.useApp()

  const { contentWidth } = useModel('Global')
  const [FormList, setFormList] = useState([])
  const [initialValues, setInitialValues] = useState({})
  const [riskOptions, setRiskOptions] = useState([])
  const [isEdit, setIsEdit] = useState(false)

  useEffect(() => {
    init()
  }, [])

  useEffect(() => {
    setFormList(getDefaultFormList())
  }, [riskOptions])

  const goEdit = () => {
    setIsEdit(true)
  }

  const init = () => {
    getSetting()
    getRiskOption()
  }

  const getSetting = async () => {
    const res = await GetBasicSet()
    if (res) setPlatformInfo(res)
  }

  const getRiskOption = async () => {
    const res = await GetRiskOptions()
    console.log('GetRiskOptions', res)
    if (res) setRiskOptions(res.map(i => ({ label: i, value: i })))
  }

  const setPlatformInfo = data => {
    const formData = {
      ...data
    }
    setInitialValues(formData)
    setTimeout(() => {
      form.resetFields()
    }, 200)
  }

  const onSubmit = () => {
    form
      .validateFields()
      .then()
      .catch(err => {
        if (err.errorFields.length) {
          message.warning('请完善表单必要信息')
        }
      })
    form.submit()
  }

  const onFinish = async e => {
    const params = { ...e }

    const res = await SaveBasicSet(params)
    if (res) {
      message.success('操作成功')
      setIsEdit(false)
      getSetting()
    }
  }

  const renderFormList = list => {
    return list.map(formItem => {
      const { type, title, children, formProp, itemProp, component, options } = formItem

      switch (type) {
        case 'wrapper':
          return (
            <Card title={title} key={title} style={{ marginBottom: '16px' }}>
              {component ? component : renderFormList(children)}
            </Card>
          )
        case 'subWrapper':
          return (
            <Card
              title={title}
              key={title}
              bordered={false}
              headStyle={{ border: 'none' }}
              style={{ boxShadow: 'none' }}
              bodyStyle={{ padding: 0 }}
            >
              {component ? component : renderFormList(children)}
            </Card>
          )
        case 'devInfoConf':
          return (
            <Card
              title={title}
              key={title}
              style={{ marginBottom: '16px' }}
              headStyle={{ border: 'none', fontWeight: 400 }}
            >
              <Form.Item {...formProp} key={formProp.name} wrapperCol={{ span: 24 }}>
                {component ? component : renderFormList(children)}
              </Form.Item>
            </Card>
          )
        case 'formComponent':
          return (
            <Form.Item {...formProp} key={title}>
              {component}
            </Form.Item>
          )
        case 'input':
          return (
            <Form.Item {...formProp} key={title}>
              <Input disabled={!isEdit} {...itemProp} />
            </Form.Item>
          )
        case 'inputNumber':
          return (
            <Form.Item {...formProp} key={title}>
              <InputNumber disabled={!isEdit} {...itemProp} />
            </Form.Item>
          )
        case 'radio':
          return (
            <Form.Item {...formProp} key={title}>
              <Radio.Group disabled={!isEdit} {...itemProp.prop}>
                {options === 'vertical' ? (
                  <Space direction='vertical' style={{ paddingTop: '5px' }}>
                    {itemProp.list && itemProp.list.length
                      ? itemProp.list.map(radio => (
                          <Radio value={radio.value} key={radio.value}>
                            {radio.label}
                          </Radio>
                        ))
                      : null}
                  </Space>
                ) : itemProp.list && itemProp.list.length ? (
                  itemProp.list.map(radio => (
                    <Radio value={radio.value} key={radio.value}>
                      {radio.label}
                    </Radio>
                  ))
                ) : null}
              </Radio.Group>
            </Form.Item>
          )
        case 'upload':
          return (
            <Form.Item {...formProp} key={title}>
              <Upload disabled={!isEdit} {...itemProp} className={styles.goods_desc_upload} />
            </Form.Item>
          )
        case 'checkbox':
          return (
            <Form.Item {...formProp} key={title}>
              <CheckboxGroup disabled={!isEdit} {...itemProp} />
            </Form.Item>
          )
        case 'select':
          return (
            <Form.Item {...formProp} key={title}>
              <Select disabled={!isEdit} {...itemProp.prop} />
            </Form.Item>
          )
      }
    })
  }

  const formatExtra = () => {
    return !isEdit
      ? [
          <Button key='goedit' htmlType='reset' onClick={goEdit}>
            编辑
          </Button>
        ]
      : [
          <Button key='reset' htmlType='reset' onClick={getSetting}>
            重置
          </Button>,
          <Button key='submit' type='primary' onClick={onSubmit}>
            保存
          </Button>
        ]
  }

  useEffect(() => {
    document.getElementsByClassName('ant-page-header')[0].style.width = `${contentWidth}px`
  }, [contentWidth])

  return (
    <div className={styles.page_wrapper}>
      <PageContainer
        header={{
          fixedHeader: true,
          title: (
            <div className={styles.header_title}>
              <span>{isEdit ? '编辑' : '设置'}</span>
              <Divider type='vertical' />
              <span className={styles.header_desc}>平台设置管理页</span>
            </div>
          ),
          extra: formatExtra()
        }}
      >
        <Form form={form} name='goods_form' {...formItemLayout} onFinish={onFinish} initialValues={initialValues}>
          {renderFormList(FormList)}

          <Card title={'进件设置'} key={'进件设置'} style={{ marginBottom: '16px' }}>
            <Form.Item name='can_rejected_create_order' valuePropName='checked' label='' colon>
              <Checkbox disabled={!isEdit}>审核拒绝的客户不允许提交订单</Checkbox>
            </Form.Item>
            <Form.Item shouldUpdate>
              {() => {
                let disabledInput = form.getFieldValue('can_rejected_create_order') && isEdit
                return (
                  <>
                    <Form.Item
                      {...formItemLayout}
                      name='rejected_create_order_after_days'
                      label='限制时间 : '
                      extra='审核拒绝的客户在限制时间内将无法再提交订单'
                      rules={[
                        {
                          required: disabledInput,
                          message: '请输入限制时间'
                        }
                      ]}
                    >
                      <Input placeholder='请输入' allowClear disabled={!disabledInput} addonAfter='天' />
                    </Form.Item>
                  </>
                )
              }}
            </Form.Item>

            <Form.Item name='open_user_order_num_limit' valuePropName='checked' label='' colon>
              <Checkbox disabled={!isEdit}>限制用户下单次数</Checkbox>
            </Form.Item>
            <Form.Item shouldUpdate>
              {() => {
                let disabledInput = form.getFieldValue('open_user_order_num_limit') && isEdit
                return (
                  <>
                    <Form.Item
                      {...formItemLayout}
                      name='limit_order_num'
                      label='限制次数 : '
                      extra='限制每个用户可以提交的订单总次数（未支付订单、待审核订单），超出后无法提交订单'
                      rules={[
                        {
                          required: disabledInput,
                          message: '请输入限制次数'
                        }
                      ]}
                    >
                      <Input placeholder='请输入' allowClear disabled={!disabledInput} addonAfter='次/人' />
                    </Form.Item>
                  </>
                )
              }}
            </Form.Item>
          </Card>
        </Form>
      </PageContainer>
    </div>
  )
}
